package pCloud.service;

import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import pCloud.message.Message;
import pCloud.message.NumberMessage;
import pCloud.message.cloud.DataMessage;

/**
 * Handle messages sent from the proxy back to the client
 * 
 */
public class DataOwnerClientProtocol extends ProtocolHandle {

	int counter = 0;
	boolean printingData = true;
	long startTime; 
	String timeLogFile=null; 
	int nReplies = 1; //number of replies expected. This depends on the number of requested resources and 
						//if there's joining condition. 
	
	@Override
	public void receive(Object o) throws Exception {
		System.err.println("RECEIVED msgw ... Should not happen");
		//System.out.println("End_time = " + System.currentTimeMillis());		
		handleDataMessage((Message)o);

		// this.conn.close();
		// this.communicator.removeConnection(this);
	}

	@Override
	public void send(Object m) throws Exception {
		conn.send(m);
	}

	private void handleDataMessage(Message msg){
		DataMessage dm = (DataMessage)msg;
		System.out.println("Data message received: "+dm.getValue());
	}
	
	public void setNumberOfReplies(int nReplies){
		this.nReplies = nReplies;
		System.out.println("Number of replies = "+nReplies);
	}
	
	public void setPrintingDataOption(boolean b){
		this.printingData = b;
	}
	
	public void setTimeLogFile(String fileName){
		this.timeLogFile = fileName;
	}
	
	public void initStartTime(){
		this.startTime = System.currentTimeMillis();
	}
	
	private void outputTime(String messageClassName) throws IOException{
		long endTime = System.currentTimeMillis();
		double time = (endTime - startTime)*1.0/1000;
		if (this.timeLogFile!=null){
			PrintWriter writer = new PrintWriter(new FileWriter(this.timeLogFile,true));			
			writer.println(messageClassName+" "+this.startTime+" - "+endTime+" - "+time);
			writer.close();
		}
		else
			System.out.println("Time: "+this.startTime+" - "+endTime+ " - "+time);
		
	}
}
